package com.hui.account.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hui.account.R;
import com.hui.account.activity.RecordModActivity;
import com.hui.account.adapter.FileAdapter;
import com.hui.account.database.SQLManage;
import com.hui.account.entity.FileEntity;
import com.hui.account.entity.FileVo;
import com.hui.account.entity.RecordEntity;
import com.hui.account.entity.UserEntity;
import com.hui.account.utils.ButtonUtils;
import com.hui.account.utils.CommonUtils;
import com.hui.account.utils.FileUtils;
import com.hui.account.utils.ImageUtils;
import com.hui.account.utils.TimeUtils;
import com.hui.account.utils.ToastUtils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 备份文件选择器
 */
public class FileDialog extends Dialog implements View.OnClickListener {

    Context context;

    Button cancelBtn, chooseBtn;

    ListView fileList; // 备份文件列表

    List<FileVo> data; // 备份文件

    FileAdapter adapter;

    public FileDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_file);

        // 1、初始化页面
        initView();

        // 2、初始化数据
        initData();

        // 3、点击事件
        onClickFileList();
    }

    /**
     * 初始化页面
     */
    private void initView() {
        cancelBtn = findViewById(R.id.dialog_file_cancel);
        chooseBtn = findViewById(R.id.dialog_file_choose);
        fileList = findViewById(R.id.dialog_file_data);

        cancelBtn.setOnClickListener(this);
        chooseBtn.setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        data = new ArrayList<>();

        File file = new File(CommonUtils.BACKUP_PATH);
        List<File> files = FileUtils.getListFiles(file);
        if (files.size() > 0) {
            for (File f : files) {
                data.add(new FileVo(f.getName(), FileUtils.transferFileSize(f.length()), TimeUtils.longTransferTime(f.lastModified())));
            }
        }

        // 引入备份文件适配器
        adapter = new FileAdapter(context, data);
        fileList.setAdapter(adapter);
    }

    /**
     * 备份文件适配器点击事件
     */
    private void onClickFileList() {
        fileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!ButtonUtils.isFastDoubleClick()) {
                    try {
                        // 1、获取到当前记录
                        FileVo file = data.get(i);
                        if (null != file) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setTitle("恢复数据").setMessage("还原至：" + file.getTime() + "\n\n" + file.getName()).setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @RequiresApi(api = Build.VERSION_CODES.N)
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    // 执行数据恢复
                                    boolean b = recoverData(file);
                                    if (b) {
                                        ToastUtils.success(context, "数据恢复成功", Gravity.CENTER, 0, 0);
                                    } else {
                                        ToastUtils.error(context, "数据恢复失败", Gravity.CENTER, 0, 0);
                                    }
                                }
                            });
                            builder.create().show();
                        }
                    } catch (Exception e) {
                        Log.e(CommonUtils.TAG, "===> 【恢复数据】 恢复数据" + e.getMessage());
                    }
                }
                cancel();
            }
        });
    }

    /**
     * 执行数据恢复
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private boolean recoverData(FileVo f) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(CommonUtils.BACKUP_PATH + f.getName())));
            StringBuilder builder = new StringBuilder();
            br.lines().forEach(builder::append);
            br.close();

            List<UserEntity> users = null;
            List<RecordEntity> records = null;
            List<FileEntity> files = null;

            if (builder.length() > 0 && !"null".equals(builder.toString()) && !"".equals(builder.toString())) {
                Gson gson = new Gson();
                JSONObject object = new JSONObject(builder.toString());

                if (!object.isNull("users")) {
                    String obj = (String) object.get("users");
                    users = gson.fromJson(obj, new TypeToken<List<UserEntity>>() {
                    }.getType());
                }

                if (!object.isNull("records")) {
                    String obj = (String) object.get("records");
                    records = gson.fromJson(obj, new TypeToken<List<RecordEntity>>() {
                    }.getType());
                }

                if (!object.isNull("files")) {
                    String obj = (String) object.get("files");
                    files = gson.fromJson(obj, new TypeToken<List<FileEntity>>() {
                    }.getType());
                }
            }

            SQLManage.clearDataBase(); // 清空数据库并且重新设置主键

            if (null != users) {
                for (UserEntity user : users) {
                    SQLManage.addUser(user);
                }
            }

            if (null != records) {
                for (RecordEntity record : records) {
                    SQLManage.addRecord(record);
                }
            }

            if (null != files) {
                for (FileEntity file : files) {
                    SQLManage.addFile(file);
                }
            }

            return true;
        } catch (Exception e) {
            Log.e(CommonUtils.TAG, "恢复数据失败:" + e.getMessage());
        }
        return false;
    }

    /**
     * 分页查询数据
     */
    public List<FileEntity> getFiles() {
        int curPage = 0; // 起始页码
        int pageSize = 500; // 每页查询最大数
        List<FileEntity> list = new ArrayList<>();
        boolean flag = true;
        while (flag) {
            List<FileEntity> records = SQLManage.getFiles(curPage, pageSize);
            if (records.size() > 0) {
                list.addAll(records);
                if (records.size() == pageSize) {
                    curPage += pageSize;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return list;
    }

    /**
     * 设置 dialog尺寸与屏幕尺寸保持一致
     */
    public void setDialogSize() {
        Window window = getWindow();
        Display display = window.getWindowManager().getDefaultDisplay();

        WindowManager.LayoutParams params = window.getAttributes();
        params.width = display.getWidth();
        params.gravity = Gravity.BOTTOM;
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setAttributes(params);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dialog_file_cancel:
                cancel();
                break;
            case R.id.dialog_file_choose:
                break;
        }
    }
}
